#!/bin/bash

# 定义颜色变量
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 恢复默认颜色

# 可自定义配置参数
TIMEZONE="Asia/Shanghai"
LANG_SETTING="en_US.UTF-8"
ALIYUN_NTP=("ntp.aliyun.com" "ntp1.aliyun.com")

# 错误处理函数
handle_error() {
    echo -e "${RED}错误发生在第 $1 行，退出状态码 $2${NC}"
    exit $2
}

trap 'handle_error $LINENO $?' ERR

check_root() {
    if [[ $EUID -ne 0 ]]; then
        echo -e "${RED}错误：本脚本需要root权限执行${NC}"
        exit 1
    fi
}

setup_basic() {
    echo -e "${YELLOW}[1/10] 正在更换软件源...${NC}"
    sed -e 's|^mirrorlist=|#mirrorlist=|g' \
       -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://mirrors.aliyun.com/rockylinux|g' \
       -i.bak /etc/yum.repos.d/[Rr]ocky*.repo
    dnf makecache -y
    echo -e "${GREEN}软件源已成功更换为阿里云镜像${NC}"
}

setup_time() {
    echo -e "${YELLOW}[2/10] 配置系统时区...${NC}"
    timedatectl set-timezone ${TIMEZONE}
    echo -e "当前时间: $(date)"
    echo -e "${GREEN}时区已设置为 ${TIMEZONE}${NC}"

    echo -e "${YELLOW}[3/10] 配置时间同步服务...${NC}"
    if ! rpm -q chrony >/dev/null; then
        dnf install -y chrony
    fi

    # 备份并生成新配置
    cp /etc/chrony.conf /etc/chrony.conf.bak
    cat > /etc/chrony.conf << EOF
# 阿里云NTP服务器配置
server ${ALIYUN_NTP[0]} iburst
server ${ALIYUN_NTP[1]} iburst

# 启用内核时间同步
rtcsync

# 允许同步时间差异
makestep 1.0 3

# 日志记录
logdir /var/log/chrony
EOF

    systemctl enable chronyd --now
    chronyc -a makestep >/dev/null
    echo -e "${GREEN}时间同步已配置完成${NC}"
}

security_settings() {
    echo -e "${YELLOW}[5/10] 处理防火墙配置...${NC}"
    systemctl stop firewalld
    systemctl disable firewalld
    echo -e "已禁用 firewalld"

    echo -e "${YELLOW}[6/10] 禁用SELinux...${NC}"
    setenforce 0
    sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
    if command -v grubby &> /dev/null; then
        grubby --update-kernel ALL --args selinux=0
    fi
    echo -e "SELinux 已永久禁用"
}

install_packages() {
    echo -e "${YELLOW}[7/10] 安装EPEL仓库...${NC}"
    dnf install -y epel-release
    dnf makecache

    echo -e "${YELLOW}[8/10] 安装基础工具包...${NC}"
    dnf install -y net-tools tree lrzsz vim-enhanced unzip telnet bash-completion
    echo -e "${GREEN}已安装：网络工具/目录树/文件传输/增强版Vim/解压工具${NC}"
}

cleanup() {
    echo -e "${YELLOW}[9/10] 清理缓存...${NC}"
    dnf autoremove -y
    dnf clean all
}

final_check() {
    echo -e "${YELLOW}[10/10] 最终系统检查...${NC}"
    echo -e "时间同步状态："
    chronyc tracking | grep "Leap status"
    echo -e "\n本地化设置："
    locale
    echo -e "\n安全配置："
    sestatus
}

main() {
    check_root
    set -euo pipefail
    
    setup_basic       # 步骤1
    setup_time        # 步骤2-3
    security_settings # 步骤5-6
    install_packages  # 步骤7-8
    cleanup           # 步骤9
    final_check       # 步骤10

    echo -e "\n${GREEN}系统初始化全部完成！${NC}"
    echo -e "建议操作："
    echo -e "1. 验证时间同步：${YELLOW}chronyc sources -v${NC}"
    echo -e "2. 检查语言环境：${YELLOW}locale -a${NC}"
    echo -e "3. 建议执行：${GREEN}reboot${NC} 重启系统"
}

main
